package com.ganbo.stock.service.impl;


import com.ganbo.stock.entity.Fund;
import com.ganbo.stock.utils.RestTemplateUtils;
import com.ganbo.stock.dto.FundFetchDataDTO;
import com.ganbo.stock.dto.FundFetchItemDTO;
import com.ganbo.stock.enums.FundType;
import com.ganbo.stock.enums.OrderType;
import com.ganbo.stock.repository.FundRepository;
import com.ganbo.stock.repository.FundStockLastRepository;
import com.ganbo.stock.repository.FundStockRepository;
import com.ganbo.stock.service.FundService;
import com.ganbo.stock.service.FundStockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class FundServiceImpl extends BaseService implements FundService {

    @Autowired
    FundRepository fundRepository;
    @Autowired
    FundStockLastRepository fundStockLastRepository;
    @Autowired
    FundStockRepository fundStockRepository;
    @Autowired
    RestTemplateUtils restTemplateUtils;
    @Autowired
    FundStockService fundStockService;

    //数据来源：https://danjuanfunds.com/rank/performance
    //https://danjuanfunds.com/djapi/v3/filter/fund?type=1&order_by=1w&size=20&page=1
    private final String fundTopUrl = "https://danjuanfunds.com/djapi/v3/filter/fund?fundType&orderByType&size=30&page=1";

    @Transactional
    public void init() {

        fundRepository.deleteAll();
        fundStockRepository.deleteAll();
        fundStockLastRepository.deleteAll();
        log.info("清除上一次的数据成功,开始拉取最新的数据...");

        int count = 1;
        List<Integer> fetchFundTypes = Arrays.asList(1, 3, 5); //参考枚举：FundType，这里只抓取：股票型、混合型、指数型
        List<String> fetchFundOrderByType = Arrays.asList("1w", "1m", "3m");    //参考枚举：OrderType，一周，一月，三月

//        //为了开发方便，少拉取一些数据
//        List<Integer> fetchFundTypes = Arrays.asList(1); //参考枚举：FundType，这里只抓取：股票型、混合型、指数型
//        List<String> fetchFundOrderByType = Arrays.asList("1w");    //参考枚举：OrderType，一周，一月，三月
        long startTime = System.currentTimeMillis();

        Fund fund;
        Map<String, String> params = new HashMap<>();
        for (int i = 0; i < fetchFundTypes.size(); i++) {
            Integer fundType = fetchFundTypes.get(i);
            for (int j = 0; j < fetchFundOrderByType.size(); j++) {
                String orderBy = fetchFundOrderByType.get(j);
                String url = getUrl(fundType, orderBy, fundTopUrl);
                FundFetchDataDTO fundFetchDataDTO = restTemplateUtils.get(url, params, FundFetchDataDTO.class);

                List<FundFetchItemDTO> items = fundFetchDataDTO.getData().getItems();
                if (CollectionUtils.isEmpty(items)) continue;
                for (FundFetchItemDTO item : items) {
                    fund = new Fund();
                    fund.setCode(item.getFd_code());
                    fund.setName(item.getFd_name());
                    fund.setYield(item.getYield());
                    fund.setType(item.getSf_type());
                    fund.setTypeName(FundType.findDescByCode(item.getSf_type()));
                    fund.setUnitNav(item.getUnit_nav());
                    fund.setCycle(OrderType.findDescByCode(orderBy));
                    fundRepository.save(fund);
                    log.info("基金抓取===>count:{},抓取到：{},{}===>{}", (++count), FundType.findDescByCode(fundType), OrderType.findDescByCode(orderBy), item.getFd_name());
                }
            }
        }
        log.info("最新排行基金数据拉取完毕，累积条数：{},耗时:{}秒", count, (System.currentTimeMillis() - startTime) / 1000);
    }


    private String getUrl(Integer fundType, String orderByType, String url) {
        String tempUrl = url.replace("fundType", "type=" + fundType);
        tempUrl = tempUrl.replace("orderByType", "order_by=" + orderByType);
        return tempUrl;
    }
}
